import chalk from 'chalk';
import * as puppeteer from 'puppeteer';
import shell from 'shelljs';
import { getParams } from '../utils';

const log = console.log;

export default async function () {
  const account = 'liming.zong';
  const password = 'hooks16.8';

  const params = getParams();

  const branchName = params[0] || 'develop';
  const envName = params[1] || 'dev';
  const projectName = params[2] || 'global-dev-otc-client';

  // if (!params || (params && params.length === 0)) {
  //   log(chalk.red('指令缺失,示例 qps deploy 分支名称 发布环境(dev/test)'));
  //   shell.exit();
  // }

  // if (params[1] !== 'dev') {
  //   log(chalk.red(`暂不支持${envName}环境`));
  //   shell.exit();
  // }

  console.log('项目:' + projectName, '分支:' + branchName, '环境:' + envName);

  const browser = await puppeteer.launch({
    headless: 'new',
    args: [
      '--no-sandbox',
      '--disable-setuid-sandbox',
      '--disable-blink-features=AutomationControlled',
    ],
    dumpio: false,
  });

  const page = await browser.newPage();

  log(chalk.yellow('开始初始化'));

  await page.goto(
    `http://jenkins.ebonex.io/view/global-dev/job/global-dev-broker/job/${projectName}/build?delay=0sec`,
  );

  await page.type('input[name="username"]', account);
  await page.type('input[name="password"]', password);

  await page.click('input[name="login"]');

  await page.waitForTimeout(2000);

  try {
    await page.click(`option[value="origin/${branchName}"]`);
  } catch (error) {
    log(chalk.red(`${branchName}分支不存在,请检查分支名称`));
    shell.exit(1);
  }

  await page.waitForTimeout(500);

  await page.click('button[type="submit"]');

  log(chalk.yellow('构建中...'));

  await page.waitForTimeout(5000);

  log(chalk.green('发布成功'));
  shell.exit();
}
